import { createApp } from 'vue'
import CustomMessageBox from '@/components/CustomMessageBox.vue'
import ElementPlus from 'element-plus'

let messageBoxInstance = null
let messageBoxContainer = null

const createMessageBoxContainer = () => {
  if (!messageBoxContainer) {
    messageBoxContainer = document.createElement('div')
    messageBoxContainer.id = 'custom-message-box-container'
    document.body.appendChild(messageBoxContainer)
  }
  return messageBoxContainer
}

const showMessageBox = (options) => {
  return new Promise((resolve, reject) => {
    // 如果已有对话框实例，先关闭它
    if (messageBoxInstance) {
      messageBoxInstance.unmount()
      messageBoxInstance = null
    }

    const container = createMessageBoxContainer()
    
    // 创建新的对话框实例
    messageBoxInstance = createApp(CustomMessageBox, {
      ...options,
      onConfirm: () => {
        resolve('confirm')
        if (messageBoxInstance) {
          messageBoxInstance.unmount()
          messageBoxInstance = null
        }
      },
      onCancel: () => {
        resolve('cancel')
        if (messageBoxInstance) {
          messageBoxInstance.unmount()
          messageBoxInstance = null
        }
      },
      onClose: () => {
        resolve('close')
        if (messageBoxInstance) {
          messageBoxInstance.unmount()
          messageBoxInstance = null
        }
      }
    })
    
    messageBoxInstance.use(ElementPlus)
    messageBoxInstance.mount(container)
  })
}

const MessageBox = {
  alert: (message, title = '提示', options = {}) => {
    return showMessageBox({
      message,
      title,
      type: options.type || 'info',
      showCancelButton: false,
      confirmButtonText: options.confirmButtonText || '确定',
      ...options
    })
  },
  confirm: (message, title = '确认', options = {}) => {
    return showMessageBox({
      message,
      title,
      type: options.type || 'warning',
      showCancelButton: true,
      confirmButtonText: options.confirmButtonText || '确定',
      cancelButtonText: options.cancelButtonText || '取消',
      ...options
    })
  },
  prompt: (message, title = '输入', options = {}) => {
    // 简化版本，暂时使用alert
    return showMessageBox({
      message,
      title,
      type: options.type || 'info',
      showCancelButton: true,
      confirmButtonText: options.confirmButtonText || '确定',
      cancelButtonText: options.cancelButtonText || '取消',
      ...options
    })
  }
}

export default MessageBox